import tkinter as tk
root = tk.Tk()
import pgzrun
from vec import Vec2
import math
import random
WIDTH = 500
HEIGHT = 500

PEN_COLOR = (0, 200, 0)
BACK_COLOR = (0, 0, 0)
ptL = []
length = 400
pt_mid = Vec2(WIDTH / 2, HEIGHT / 2)
y_offset = length / math.sqrt(3)
pt_a = Vec2(pt_mid.x, pt_mid.y - y_offset)
pt_d = Vec2(pt_mid.x, pt_mid.y + length / 2 / math.sqrt(3))
pt_b = Vec2(pt_d.x - length / 2, pt_d.y)
pt_c = Vec2(pt_d.x + length / 2, pt_d.y)

for i in (pt_a, pt_b, pt_c):
    ptL.append(i)


def fractal(ptList):
    i = 0
    while True:
        if i == len(ptList) - 1:
            line_fractal(ptL, i, 0)
            break
        else:
            i = line_fractal(ptL, i, i + 1)

def line_fractal(ptList, a, b):
    pt1 = ptL[a] * 2 / 3 + ptL[b] / 3
    midPt = (ptL[a] + ptL[b]) / 2
    dir = ptL[b] - ptL[a]
    dir.normalize()
    vdir = Vec2(0, 0)
    n = random.randint(1, 100)
    vdir.x = -dir.y
    vdir.y = dir.x

    dist = (ptL[b] - ptL[a]).length() / 3 / 2 * math.sqrt(3)
    pt2 = midPt + vdir * dist
    pt3 = ptL[a] / 3 + ptL[b] * 2 / 3
    ptL.insert(a + 1, pt3)
    ptL.insert(a + 1, pt2)
    ptL.insert(a + 1, pt1)
    return  a + 4
#----------#
fn = 0
def Add():
    global fn
    fn += 1
    for i in range(fn):
        fractal(ptL)
a = tk.Button(
    root,
    width=10,
    text="add",
    command=Add
)
a.pack()
def Sub():
    global fn
    fn -= 1
    for i in range(4):
        fractal(fn)
b = tk.Button(
    root,
    width=10,
    text="sub",
    command=Sub
)
a.pack()
b.pack()
#----------#

def draw():
    screen.fill(BACK_COLOR)
    for i in range(len(ptL)):
        if i == len(ptL) - 1:
            screen.draw.line(ptL[i].raw_get(), ptL[0].raw_get(), PEN_COLOR)
        else:
            screen.draw.line(ptL[i].raw_get(), ptL[i + 1].raw_get(), PEN_COLOR)

pgzrun.go()